package u.hnx.admin.security.utils;

import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import u.hnx.admin.security.api.HttpStatusAPI;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class ResponseUtil implements HttpStatusAPI {
    private final ObjectMapper objectMapper;
    public  void writeJSON(HttpServletResponse response, Map<String,Object> map){
        try{
            String content = objectMapper.writeValueAsString(map);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            if(StrUtil.isNotBlank(content)) {
                write(response, content);
            }
        }catch (Exception ex){
            throw new RuntimeException(ex.getMessage());
        }

    }
    public  void write(HttpServletResponse response, String text) {
        Writer writer = null;
        try {
            writer = response.getWriter();
            writer.write(text);
            writer.flush();
        } catch (IOException e) {
            throw new UtilException(e);
        } finally {
            IoUtil.close(writer);
        }
    }
    public void printFail(HttpServletRequest request, HttpServletResponse response, Integer code, String msg) {
        writeJSON(response, getJson(code,msg));
    }

    public void printFail(HttpServletRequest request, HttpServletResponse response, String msg) {
        printFail(request,response,DEFAULT_HTTP_ERROR_CODE,msg);
    }
    private Map<String,Object> getJson(Integer code,String msg){
        Map<String,Object> map = new HashMap<>();
        map.put(CODE_TAG,code);
        map.put(MSG_TAG,msg);
        return map;
    }
}
